package ynu.edu.user.controller;

import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynu.edu.api.client.PermissionFeignClient;
import ynu.edu.common.domain.R;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
    
    @Autowired
    private PermissionFeignClient permissionFeignClient;
    
    private final Random random = new Random();

    /**
     * 测试接口 - 模拟服务响应
     * 1. 随机延迟 0-2 秒
     * 2. 30% 概率抛出异常
     * 3. 记录详细的请求日志
     */
    @GetMapping("/simulate")
    public R<String> simulateService(@RequestParam(required = false) Long userId) {
        String requestId = String.format("REQ-%d", System.currentTimeMillis());
        log.info("[{}] 收到测试请求，用户ID: {}", requestId, userId);
        
        try {
            // 模拟随机延迟
            int delay = random.nextInt(2000);
            log.info("[{}] 模拟处理延迟: {}ms", requestId, delay);
            TimeUnit.MILLISECONDS.sleep(delay);
            
            // 30% 概率模拟错误
            if (random.nextDouble() < 0.3) {
                log.error("[{}] 模拟服务异常", requestId);
                throw new RuntimeException("模拟的服务异常");
            }
            
            String response = String.format("处理成功 - 用户ID: %s, 延迟: %dms", userId, delay);
            log.info("[{}] 请求处理完成: {}", requestId, response);
            return R.ok(response);
            
        } catch (InterruptedException e) {
            log.error("[{}] 处理被中断", requestId, e);
            return R.error("服务处理被中断");
        } catch (Exception e) {
            log.error("[{}] 处理发生异常: {}", requestId, e.getMessage());
            return R.error("服务处理异常: " + e.getMessage());
        }
    }

    @GetMapping("/permissions/{userId}")
    public R<List<String>> testGetPermissions(@PathVariable Long userId) {
        try {
            List<String> permissions = permissionFeignClient.getPermissions(userId);
            return R.ok(permissions);
        } catch (RequestNotPermitted e) {
            log.warn("请求被限流，用户ID：{}", userId);
            return R.ok(List.of()); // 返回空列表，表示限流
        } catch (Exception e) {
            log.error("获取权限失败，用户ID：{}，异常：{}", userId, e.getMessage());
            return R.error("获取权限失败");
        }
    }

    @GetMapping("/roles/{userId}")
    public R<List<String>> testGetRoles(@PathVariable Long userId) {
        try {
            List<String> roles = permissionFeignClient.getRoles(userId);
            return R.ok(roles);
        } catch (Exception e) {
            log.error("获取角色失败，用户ID：{}，异常：{}", userId, e.getMessage());
            return R.error("获取角色失败");
        }
    }

    @PostMapping("/default-role/{userId}")
    public R<String> testAssignDefaultRole(@PathVariable Long userId) {
        try {
            permissionFeignClient.assignDefaultRole(userId);
            return R.ok("默认角色分配成功");
        } catch (Exception e) {
            log.error("分配默认角色失败，用户ID：{}，异常：{}", userId, e.getMessage());
            return R.error("分配默认角色失败");
        }
    }
    
}